import axios from 'axios'
import {Toast} from 'vant'
import router from "@/router";
import {clearToast} from "@/utils/index";

const baseUrl = process.env.NODE_ENV === 'development' ? '/api' : window.origin + '/system-domain/'
// 创建axios实例
const service = axios.create({
    timeout: 30000, // 请求超时时间ss
    baseURL: baseUrl
})
// request拦截器
service.interceptors.request.use(config => {
    const token = sessionStorage.getItem('token')
    config.headers.token = token
    return config
}, error => {
    Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(
    async response => {
        const {data} = response
        const successCode = [200, 201,1]
        if (data.code && successCode.indexOf(data.code) === -1) {
            if (data.code === 1001) {
                Toast(data.msg);
                router.push('/login')
                sessionStorage.clear()
                return
            }
            Toast(data.message);
        }
        return response.data
    },
    error => {
        console.error(error)
        clearToast()
        // 接口错误返回错误码
        return {code: 0}
    }
)

export default service
